#!/usr/bin/python3

import RPi.GPIO as RG
import lirc


class CarBehavior:

    def __init__(self, power_pin):
        self.is_run = False
        RG.setup(power_pin, RG.OUT)
        self.power_pin = power_pin

    def on_power(self):
        if self.is_run:
            pass
        else:
            RG.output(self.power_pin, RG.HIGH)
            self.is_run = True

    def close_power(self):
        if self.is_run:
            self.is_run = False
            RG.output(self.power_pin, RG.LOW)
        else:
            pass


class Main:

    def __init__(self):
        RG.cleanup()
        RG.setmode(RG.BCM)
        self.ic = lirc.init("pylirc")

    @staticmethod
    def close():
        lirc.deinit()
        RG.cleanup()
        exit(0)

    def loop_lirc(self):
        car = CarBehavior(22)
        try:
            while True:
                ic_code = lirc.nextcode()
                if ic_code == ["KEY_NUMERIC_1"]:
                    car.on_power()
                elif ic_code == ["KEY_NUMERIC_2"]:
                    car.close_power()
                elif ic_code == ["KEY_NUMERIC_3"]:
                    self.close()
        except KeyboardInterrupt as e:
            print(e)
            lirc.deinit()
            RG.cleanup()


if __name__ == "__main__":
    m = Main()
    m.loop_lirc()
